package ru.papergames.web.services.users;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.validation.Errors;
import ru.common.hibernate.HibernateAction;
import ru.papergames.common.form.PcPlayerForm;
import ru.papergames.common.model.PcPlayer;
import ru.papergames.web.forms.UserForm;
import ru.papergames.web.model.User;

import java.util.List;

/**
 * TODO: add description
 * Date: 22.12.11 23:15
 *
 * @author Alexander Troshanin
 */
public class RegisterNewPcPlayer implements HibernateAction<Void> {

    private final PcPlayerForm pcPlayerForm;

    private final List<String> errors;

    public RegisterNewPcPlayer(PcPlayerForm pcPlayerForm, List<String> errors) {
        this.pcPlayerForm = pcPlayerForm;
        this.errors = errors;
    }

    @Override
    public Void execute(Session session) {
        Query q1 = session.createQuery("select x from AbstractPlayer x where x.username=:username");
        q1.setString("username", pcPlayerForm.getUsername());
        List lst1 = q1.list();
        if (lst1 != null && lst1.size() > 0) {
            errors.add("registration.fail.username.already.used");
        }
        Query q2 = session.createQuery("select x from AbstractPlayer x where x.email=:email");
        q2.setString("email", pcPlayerForm.getEmail());
        List lst2 = q2.list();
        if (lst2 != null && lst2.size() > 0) {
            errors.add("registration.fail.email.already.used");
        }
        if (!errors.isEmpty()) {
            return null;
        }
        PcPlayer pcPlayer = new PcPlayer();
        pcPlayer.setUsername(pcPlayerForm.getUsername());
        pcPlayer.setPassword(pcPlayerForm.getPassword());
        pcPlayer.setFullName(pcPlayerForm.getFullName());
        pcPlayer.setEmail(pcPlayerForm.getEmail());
        session.save(pcPlayer);
        pcPlayerForm.setId(pcPlayer.getId());
        return null;
    }
}
